//会员管理——会员列表
var starttime = ""; //开始时间
var endtime = ""; //结束时间
var sortfild = ""; //排序的关键字
var sortway = ""; //排序：升序、降序
var ttname = "用户列表";
var tab="";//商家升级为农家乐，还是景区
$(function() {

	//获取主题游类型
	getThemelist();
	//获取景区游玩类型
	getSecPlayTypelist();
    //获取农家乐商户类型
    getAllfarmMertype();
    //获取景区商户类型
    getAllSerMertype();
    //获取适合人群类型
    getAllCrowd();

	 //下拉框
    $(document).on('click', ".my_select_ul li", function () {
        $(this).parent().siblings("div").find("span").html($(this).text());
        $(this).parent().siblings("div").find("span").attr("value", $(this).attr("value"));
        if($(this).parent().siblings("div").find("span").hasClass("user_role_name")){
            if($(this).text() == "全部"){
                $(".user_role_name").text("角色");
            }
		}
        //获取数据
        $("#first_button").click();
    })
	//排序 
	$(".list_sort_tab").click(function() {
		sortfild = $(this).attr("value");
		if($(this).find("i").hasClass("icon_downs")) {
			$(this).find("i").removeClass("icon_downs");
			$(this).find("i").addClass("icon_ups");
			sortway = "asc";
		} else {
			$(this).find("i").removeClass("icon_ups");
			$(this).find("i").addClass("icon_downs");
			sortway = "desc";
		}
		//必须要，否则排序则不能调用该方法  使用该句，当点击排序，就同时点击了 第一页的按钮，自动调用分页的效果，
        $("#first_button").click();
	});

	//悬浮显示 当宽度小于 文字宽度时，则鼠标移到该内容时，悬浮显示，将文字全部显示出来
	$(document).on("mouseover", ".show_tips", function() {
		if($(this).width() > $(this).parent().width()) {
			layer.tips($(this).html(), $(this), {
				tips: [1, '#3595CC'],
				time: 0
			})
		}
	});
	$(document).on("mouseout", ".show_tips", function() {
		layer.closeAll('tips');
	});

	//全选中或全不选
	$("#checkAll").click(function() {
		if($(this).is(':checked')) {
			$(".checkbox").prop("checked", true);
		} else {
			$(".checkbox").prop("checked", false);
		}
	})

	/*切换搜索条件*/
	$("#conditional_search").find("li").click(function() {
		$("#search_name").text($(this).text());
		$(this).find("a").attr('value');
		$("#search_name").attr('value', $(this).find("a").attr('name'));
	});

	//时间选择
	timesearch();
	var today = new Date();
	startDate = endDate = today.format('yyyy-MM-dd');
	starttime = endtime = startDate;
	$("#date1").html(startDate + " - " + endDate);
	$(".select_time1 li ").click(function() {
		$(".select_time1 li").removeClass("blue_color");
		$(this).addClass("blue_color");
		var time = $(this).attr("name");
		if(time == "0") {
			startDate = endDate = today.format('yyyy-MM-dd');
		} else if(time == "1") {
			startDate = endDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 1).format('yyyy-MM-dd');
		} else if(time == "7") {
			startDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 6).format('yyyy-MM-dd');
			endDate = today.format('yyyy-MM-dd');
		} else if(time == "30") {
			startDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 29).format('yyyy-MM-dd');
			endDate = today.format('yyyy-MM-dd');
		}
		starttime = startDate;
		endtime = endDate;
		$("#date1").html(startDate + " - " + endDate);
		if(time == "") {
			starttime = "";
			endtime = "";
		}
		//获取数据
        getData();
	})

    //回车事件
    $('#conditional_searchinput').bind('keypress',function(event){
        if(event.keyCode == 13) {
            $("#first_button").click();
        }
    });

    //封面图片上传
    layui.use('upload', function () {
        var upload = layui.upload;
        layuiupload = upload;
        var ii = null;
        //执行实例
        var uploadInst = upload.render({
            elem: '#test1' //绑定元素
            , url: '/xw/imgfile'
            , accept: 'file'
            , before: function (obj) { //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
                ii = layer.load(2); //上传loading
            }
            , done: function (res) {
                layer.close(ii);
                //上传完毕回调
                if (res.status == 0) {
                    layer.msg("文件上传成功");
                    $("#imgPath").val(res.fileurl);
                    $('#demo1').attr('src', res.fileurl+"?x-oss-process=style/tuImgStyle"); //图片链接（base64）
                } else {
                    layer.alert("上传文件失败！", {icon: 2})
                }
            }
            , error: function () {
                //请求异常回调
                layer.close(ii);
                layer.alert("上传文件发生异常！", {icon: 2})
            }
        });
    });

    getData();

})

function getData() {
    getlist();
}

//搜索
function addgoods() {
    $("#first_button").click();
}

//数据列表
function getlist() {
    var pagesize = $("#selectPageSize1").text();
    var pageindex = $("#currentPage").text();
    var searchval=$("#conditional_searchinput").val().trim(); //搜索内容
    var field=$("#search_name").attr("value"); //搜索字段
	var user_role = $("#user_role_name").attr("value");//用户角色
    var layLoad=layer.load(2);
    $("#biuuu_city_list").empty();
    $.post('/querUserList',{"pagesize":pagesize,"pageindex":pageindex,"starttime":starttime,"endtime":endtime,"searchval":searchval,"sortfild":sortfild,"sortway":sortway,"searchkey":field,"user_role":user_role},function(value){
        layer.close(layLoad);
        if(value.status==0 && value.msg == "ok"){
            var list=value.list;
            var pagecount=value.pagecount;
            var recordcount=value.recordcount;
            $("#totalSize").html(recordcount);
            $("#totalPage").html(pagecount);
            if(list.length==0){
				$("#biuuu_city_list").prepend("<tr class=\"iframe_tr iframe_bg\"><td colspan=\"7\" style=\"width:1126px;text-align:center;\">暂无数据</td></tr>");
            }else{
                var htm="";
                for(var i=0;i<list.length;i++){
                    htm+="<tr>";
                    // htm+="<td><input type=\"checkbox\" name="+list[i].user_id+" data='"+list[i].user_encryptId+"' class=\"checkbox\"></td>";
                    htm+="<td><span class='show_tips customerdetail'>"+(list[i].user_name)+"</span></td>";
                    htm+="<td><span class='show_tips'>"+list[i].user_realName+"</span></td>";
                    htm+="<td><span class='show_tips'>"+(list[i].user_tel)+"</span></td>";
                    // htm+="<td><span class='show_tips'>"+list[i].user_mail+"</span></td>";
                    htm+="<td><span class='show_tips'>"+RoleidByRoleName(list[i].user_role)+"</span></td>";
                    htm+="<td><span class='show_tips'>"+list[i].user_createtime+"</span></td>";

                    htm+="<td class='td-manage'>";
                        if(list[i].user_role == "0"){
                            htm += "<a href=\"javascript:void(0)\" onclick=\"Upgradetomerchant('"+list[i].user_encryptId+"','"+list[i].user_tel+"','"+list[i].user_realName+"')\">升级为商家</a>";
                        }

                        if(list[i].user_role == "0"){
                            htm +="<a class=\"customerdetail\" onclick=\"question_user('"+list[i].user_id+"','"+list[i].user_encryptId+"')\">用户详情</a>";
                        }else if(list[i].user_role == "1"){
                            if(list[i].businessTypeid == "1"){
                                //农家
                                htm +="<a class=\"customerdetail\" onclick=\"question_business('"+list[i].business_encryptId+"','"+list[i].farm_encryptId+"','"+list[i].businessTypeid+"')\">农家详情</a>";
                            }else if(list[i].businessTypeid == "2"){
                                //景区
                                htm +="<a class=\"customerdetail\" onclick=\"question_business('"+list[i].business_encryptId+"','"+list[i].sec_encryptId+"','"+list[i].businessTypeid+"')\">景区详情</a>";
                            }
                         }
						htm += "<a href=\"javascript:void(0)\" onclick=\"question_edit('"+list[i].user_encryptId+"','"+list[i].user_name+"','"+list[i].user_tel+"','"+list[i].user_realName+"','"+list[i].user_mail+"','"+list[i].user_sex+"','"+list[i].user_role+"','"+list[i].user_Avatar+"','"+list[i].user_hobby_zt+"','"+list[i].user_hobby_yw+"','"+list[i].farm_encryptId+"','"+list[i].sec_encryptId+"')\">修改</a></div>";
						htm += "<a href=\"javascript:void(0)\" onclick=\"question_del('"+list[i].user_encryptId+"','"+list[i].farm_encryptId+"','"+list[i].sec_encryptId+"')\">删除</a></div>";
                    	htm += "</td>";

                    htm+="</tr>";
                }
                $("#biuuu_city_list").html(htm);

            }
        }else{
            if(value.msg==null||value.msg==""){
                layer.alert("接口出现错误！", {icon: 2})
            }else{
                layer.alert(value.msg, {icon: 2})
            }
        }
    })
}

//根据角色id转换为角色名称
function RoleidByRoleName(roleid) {
	if(roleid != null && roleid != ""){
		if (roleid == "0"){
			return "普通用户";
		}else if (roleid == "1"){
            return "商家";
        }else if (roleid == "2"){
            return "超级管理员";
        }
	}
	return "";
}

/**************************************修改，删除，新建-start*******************************************************/

//添加
function question_add() {
    layui.use('form', function () {
        var $ = layui.jquery, form = layui.form;

        var item = $("input[name=userHobbyZt]");
        item.each(function () {
            $(this).prop("checked", false);
        })
        form.render('checkbox');

        var item = $("input[name=userHobbyYw]");
        item.each(function () {
            $(this).prop("checked", false);
        })
        form.render('checkbox');

        $("input[name=sex][value='男']").prop("checked",true);

        form.render(); //更新全部
    });


    $("#add_user_encryptId").attr("value","");
	$("#admin_name").val("");//用户名
    $("#admin_name").removeAttr("readonly");//用户名
	$("#admin_phone").val("");//联系方式
	$("#realName").val("");//姓名
	$("#email").val("");//邮箱
	$("#imgPath").val("");//头像
	$("#demo1").attr("src","");//显示的头像图片
    $("#L_pass").val("");//密码
    $("#L_repass").val("");//确认密码

    $(".checkusename,.checktel").hide();
    ComOpenWin(1, "添加", "700px", 'auto', $("#newlybuildwin"), 1);
}

//修改
function question_edit(user_encryptId,user_name,user_tel,user_realName,user_mail,user_sex,user_role,user_Avatar,
                       user_hobby_zt,user_hobby_yw,farm_encryptId,sec_encryptId) {

    $(".checkusename,.checktel").hide();

    $("#add_old_role").attr("value",user_role);
	$("#add_user_encryptId").attr("value",user_encryptId);
	$("#add_farm_encryptId").attr("value",farm_encryptId);
	$("#add_sec_encryptId").attr("value",sec_encryptId);

    $("#admin_name").val(user_name);//用户名
    $("#admin_name").attr("readonly","readonly");//用户名
    $("#admin_phone").val(user_tel);//联系方式
    $("#realName").val(user_realName);//姓名
    $("#email").val(user_mail);//邮箱

    $("#imgPath").val(user_Avatar);//头像
    $("#demo1").attr("src",user_Avatar+"?x-oss-process=style/tuImgStyle");//显示的头像图片

	//修改的时候，密码默认为admin，
    $("#L_pass").val("xwdeshj@2018");//密码
    $("#L_repass").val("xwdeshj@2018");//确认密码

    layui.use('form', function () {
        var $ = layui.jquery, form = layui.form;
		//全部设置为未选
        var item = $("input[name=userHobbyZt]");
        item.each(function () {
            $(this).prop("checked", false);
        })
        form.render('checkbox');
		//全部设置为未选
        var item = $("input[name=userHobbyYw]");
        item.each(function () {
            $(this).prop("checked", false);
        })
        form.render('checkbox');


        //性别
		if(user_sex == "男"){
            $("input[name=sex][value='男']").prop("checked",true);
		}else {
            $("input[name=sex][value='女']").prop("checked",true);
		}

        //兴趣爱好(主题游)
        var user_hobbylist ="";
        user_hobbylist = user_hobby_zt.split(",");
        for (var j=0;j<user_hobbylist.length;j++){
            for(var i=0;i<allSceThemetypelist.length;i++){
                if(allSceThemetypelist[i].title==user_hobbylist[j]){
                    $("input[name=userHobbyZt][value='"+user_hobbylist[j]+"']").prop("checked",true);
                }
            }
            form.render();  //更新渲染
        }

        //兴趣爱好(游玩类型)
        var user_hobby_ywlist ="";
        user_hobby_ywlist = user_hobby_yw.split(",");
        for (var j=0;j<user_hobby_ywlist.length;j++){
            for(var i=0;i<allScePlaytypelist.length;i++){
                if(allScePlaytypelist[i].title==user_hobby_ywlist[j]){
                    $("input[name=userHobbyYw][value='"+user_hobby_ywlist[j]+"']").prop("checked",true);
                }
            }
            form.render();  //更新渲染
        }

        form.render(); //更新全部
    });

    //角色
    var user_role = 'dd[lay-value=' + user_role + ']';
    $('#user_role').siblings("div.layui-form-select").find('dl').find(user_role).click();

    ComOpenWin(1, "修改", "700px", 'auto', $("#newlybuildwin"), 1);
}

//动态验证用户是否存在
$(function () {
    $("#admin_name").bind('input blur', function() {
        var username = $(this).val().trim();
        if(username != ""){
            var ii = layer.load(2);
            $.post('/checkUsername', {
                "username": username
            }, function (data) {
                layer.close(ii);
                if (data.status == 0) {

                    $(".checkusename").show();
                    $(".checkusename").html(data.msg);
                    if(data.msg.indexOf("已被注册") != -1){

                        $(".checkusename").addClass("x-red");
                    }else {
                        $(".checkusename").addClass("x-green");
                    }
                } else {
                    if(data.msg==null||data.msg==""){
                        layer.alert("接口出现错误！", {icon: 2})
                    }else{
                        layer.alert(data.msg, {icon: 2})
                    }
                }
            })
        }

    });

    $("#admin_phone").bind('input blur', function() {
        var tel = $(this).val().trim();
        if(tel != "" && tel.length == 11){
            var ii = layer.load(2);
            $.post('/checkUsertel', {
                "tel": tel
            }, function (data) {
                layer.close(ii);
                if (data.status == 0) {

                    $(".checktel").show();
                    $(".checktel").html(data.msg);
                    if(data.errcode ==  0 ){
                        $(".checktel").addClass("x-green");
                    }else {
                        $(".checktel").addClass("x-red");
                    }
                } else {
                    if(data.msg==null||data.msg==""){
                        layer.alert("接口出现错误！", {icon: 2})
                    }else{
                        layer.alert(data.msg, {icon: 2})
                    }
                }
            })
        }
    });
})

//添加数据
function addUserSave() {
    var userreg = new RegExp(/^[a-zA-Z0-9]|[0-9a-zA-Z]{6,16}$/);//用户名只能是字母、数字 格式
	var user_encryptId = $("#add_user_encryptId").attr("value"); //用户加密id

    var reg = /^1[0|1|2|3|4|5|6|7|8|9]\d{9}$/;//电话验证
    var username = $("#admin_name").val().trim();//用户名
    var userTel = $("#admin_phone").val().trim();//电话号码
    var userRealname = $("#realName").val().trim();//姓名
    var userAvatar = $("#imgPath").val().trim();//头像
    var userSex = $('input:radio[name="sex"]:checked').attr("value");//性别
    var user_role = $("#user_role option:selected").attr("value");  //角色
    var email = $("#email").val().trim();  //邮箱

    //修改的时候，密码默认为admin
    var password = $("#L_pass").val().trim();  //密码
    var pwd = $("#L_repass").val().trim();  //确认密码

    // var userHobbyZt = new Array(); //兴趣爱好(主题)
    // $("#userHobbyZt").find("input[type=checkbox]:checked").each(function () {
    //     if ($.inArray($(this).attr("value"), userHobbyZt) == -1) {
    //         userHobbyZt.push($(this).attr("value"));
    //     }
    // });
    // var userHobbyYw = new Array(); //兴趣爱好(游玩)
    // $("#userHobbyYw").find("input[type=checkbox]:checked").each(function () {
    //     if ($.inArray($(this).attr("value"), userHobbyYw) == -1) {
    //         userHobbyYw.push($(this).attr("value"));
    //     }
    // });

    if(username == ""){
        layer.msg('用户名不能为空且由字母、数字组成！', {icon: 0,time:2000});
    }else if(!userreg.test(username)){
        layer.msg('请输入正确格式的用户名！', {icon: 0,time:2000});
    }else if(userTel == ""){
        layer.msg('联系方式不能为空！', {icon: 0,time:2000});
    }else if (!reg.test(userTel)) {
        layer.msg('请输入正确格式的手机号码！', {
            icon: 0,time:2000
        })
    }else if (userRealname == "") {
        layer.msg('请输入姓名！', {
            icon: 0,time:2000
        })
    }else if(user_role == ""){
        layer.msg('用户角色不能为空！', {icon: 0,time:2000});
    }else if(password !=  pwd){
        layer.msg('两次输入密码不一样，请重新输入！', {icon: 0,time:2000});
        $("#L_pass").val("");
        $("#L_repass").val("");
    }else if((password.length <6 || password.length>16)){
        layer.msg('密码长度应该在6-16个字符之间！', {icon: 0,time:2000});
    }else {
    	if($(".layui-layer-title").text() == "添加"){
    	    if(user_role != "1"){
                var ii = layer.load(2);
                $.post('/adduser', {
                    "username": username,
                    "userTel": userTel,
                    "userRealname": userRealname,
                    "userAvatar": userAvatar,
                    "userSex": userSex,
                    "user_role": user_role,
                    "email": email,
                    "password": password
                }, function (data) {
                    layer.close(ii);
                    if (data.status == 0 && data.msg == 'ok') {
                        layer.msg("操作成功！",{time:2000,icon:1});
                        getData();
                        mclose();
                    } else {
                        if(data.msg==null||data.msg==""){
                            layer.alert("接口出现错误！", {icon: 2})
                        }else{
                            layer.alert(data.msg, {icon: 2})
                        }
                    }
                })
            }else {
                layer.msg("请先注册为本站普通用户后，方可升级为商家！", {icon: 2,time:2000})
            }
        }else if($(".layui-layer-title").text() == "修改"){
            var farm_encryptId = $("#add_farm_encryptId").attr("value");
            var sec_encryptId = $("#add_sec_encryptId").attr("value");
            var oldRole = $("#add_old_role").attr("value");

            if( oldRole != "1" && user_role != "1" || (user_role == oldRole)){
                //非商家，之前也不知商家，现在也不是商家
                var ii = layer.load(2);
                $.post('/updateInformation', {
                    "user_encryptId": user_encryptId,
                    "user_tel": userTel,
                    "user_realName": userRealname,
                    "user_Avatar": userAvatar,
                    "user_sex": userSex,
                    "user_role": user_role,
                    "user_mail": email,
                    "user_password": password,
                    "farm_encryptId": farm_encryptId,
                    "sec_encryptId": sec_encryptId
                }, function (data) {
                    layer.close(ii);
                    if (data.status == 0 && data.msg == 'ok') {
                        layer.msg("操作成功！",{time:2000,icon:1});
                        getData();
                        mclose();
                    } else {
                        if(data.msg==null||data.msg==""){
                            layer.alert("接口出现错误！", {icon: 2})
                        }else{
                            layer.alert(data.msg, {icon: 2})
                        }
                    }
                })
            }else {
                layer.confirm('角色已发生改变，确认要修改吗,修改后该商家的所有的相关信息也会被删除，' +
                    '恢复到当前设置角色状态？', function(index) {
                    var ii = layer.load(2);
                    $.post('/updateInformation', {
                        "user_encryptId": user_encryptId,
                        "user_tel": userTel,
                        "user_realName": userRealname,
                        "user_Avatar": userAvatar,
                        "user_sex": userSex,
                        "user_role": user_role,
                        "user_mail": email,
                        "user_password": password,
                        "farm_encryptId": farm_encryptId,
                        "sec_encryptId": sec_encryptId
                    }, function (data) {
                        layer.close(ii);
                        if (data.status == 0 && data.msg == 'ok') {
                            layer.msg("操作成功！",{time:2000,icon:1});
                            getData();
                            mclose();
                        } else {
                            if(data.msg==null||data.msg==""){
                                layer.alert("接口出现错误！", {icon: 2})
                            }else{
                                layer.alert(data.msg, {icon: 2})
                            }
                        }
                    })
                });
            }
		}

    }
}


/*删除*/
function question_del(id,farm_encryptId,sec_encryptId) {
    layer.confirm('确认要删除吗？', function(index) {
        var ii = layer.load(2);
        $.post('/delInformation', {
            "user_encryptId": id,
            "farm_encryptId": farm_encryptId,
            "sec_encryptId": sec_encryptId
        }, function (data) {
            layer.close(ii);
            if (data.status == 0 && data.msg == 'ok') {
                layer.msg("操作成功！",{time:2000,icon:1});
                $("#first_button").click();
                mclose();
            } else {
                if(data.msg==null||data.msg==""){
                    layer.alert("接口出现错误！", {icon: 2})
                }else{
                    layer.alert(data.msg, {icon: 2})
                }
            }
        })
    });
}


/**
 * 批量删除提交，无法批量删除，因为无法批量删除多个商家的所有信息
 */
function delAll() {
    var farm_encryptId= "";
    var sec_encryptId= "";
    var tidsArry = new Array();
    $('input[class="checkbox"]:checked').each(function(){
        tidsArry.push($(this).attr("data"));//向数组中添加元素
    });
    if (tidsArry.length == 0){
        layer.alert("请至少选择一个要删除内容！",{icon:0});
    }else {
        layer.confirm('确认要删除吗？', function(index) {
            var ii = layer.load(2);
            $.post('/delInformation', {
                "user_encryptId": tidsArry.join(","),
                "farm_encryptId": farm_encryptId,
                "sec_encryptId": sec_encryptId
            }, function (data) {
                layer.close(ii);
                if (data.status == 0 && data.msg == 'ok') {
                    layer.msg("操作成功！",{time:2000,icon:1});
                    $("#first_button").click();
                    mclose();
                } else {
                    if(data.msg==null||data.msg==""){
                        layer.alert("接口出现错误！", {icon: 2})
                    }else{
                        layer.alert(data.msg, {icon: 2})
                    }
                }
            })
        });
    }
}

/**************************************修改，删除，新建-end*******************************************************/



/**************************************商家升级-start*******************************************************/

//升级为商家
function Upgradetomerchant(user_encryptId,user_tel,user_realName) {
    $("#upgrade_user_encryptId").attr("value",user_encryptId);
    //农家乐，景区联系方式
    $(".upgrade_tel").val(user_tel);
    //农家乐，景区法定代表人
    $(".upgrade_Legalperson").val(user_realName);

    //清空其他数据
    $("#farm_business_name,#tour_business_name").val("");
    $("#farm_business_code,#tour_business_code").val("");
    $("#farm_business_code,#tour_business_code").val("");
    $("#farm_license_url,#tour_license_url").val("");
    $("#farm_license_img,#tour_license_img").attr("src","");
    $("#farm_address,#tour_address").val("");
    $("#farm_introduce,#tour_introduce").val("");
    $("#farm_bus_line,#tour_bus_line").val("");
    $("#farm_self_driving_line,#tour_Self_driving_line").val("");
    $("#farm_remarks,#tour_remarks,#tour_Ticket").val("");

    layui.use('form', function () {
        var $ = layui.jquery, form = layui.form;

        var item = $("input[name=tourType]");
        item.each(function () {
            $(this).prop("checked", false);
        })
        form.render('checkbox');
    });

    ComOpenWin(1, "升级为商家", "1000px", 'auto', $("#MerchantupgradeWin"), 1);
}

//商家升级——确定，提交请求
function addMerchantSave() {
    tab =$(".realtime_tab").find(".layui-this").attr("value"); //当前选择的排行
    var user_encryptId =  $("#upgrade_user_encryptId").attr("value");//用户id
    console.log("tab:"+tab);
    if(tab == "1"){
        //升级为农家乐商家
        var CompanyName = $.trim($("#farm_business_name").val());//企业名称
        var business_Legal = $.trim($("#farm_Legalperson").val());//法定代表人
        var business_Credit = $.trim($("#farm_business_code").val());//统一社会信用码
        var business_license = $.trim($("#farm_license_url").val());//营业执照
        var business_tel = $.trim($("#farm_tel").val());//联系方式
        var business_create = $.trim($("#farm_start").val());//成立日期
        var business_type = $("#farm_Mertype_name").attr("data");//商户类型
        var farm_tour_type = $("#farm_Mertype option:selected").attr("value");//农家类型
        var Business_area = $("#farm_mianji option:selected").attr("value");//经营面积
        var dining_reception = $("#farm_capacity option:selected").attr("value");//用餐接待容纳
        var room = $("#farm_room option:selected").attr("value");//住宿容纳
        var scale = $("#farm_merch_scale option:selected").attr("value");//商铺规模
        var consume = $.trim($("#farm_pre_consumption").val());//人均消费
        var city = $("#farm_province option:selected").attr("value");  //城市名称
        var district = $("#farm_area option:selected").attr("value");  //区县
        var address = $.trim($("#farm_address").val());//住所
        var intr_info = $.trim($("#farm_introduce").val());//农家乐介绍
        var bus_route = $.trim($("#farm_bus_line").val());//公交路线
        var Self_route = $.trim($("#farm_self_driving_line").val());//自驾路线
        var Remarks = $.trim($("#farm_remarks").val());//备注
        var tradestatus = $("#farm_business_state option:selected").attr("value");//营业状态
        var Type_encryptId = $("#farm_Mertype option:selected").attr("encryptid");//农家类型加密id
        if(CompanyName == "" ||  CompanyName == undefined){
            layer.msg("企业名称不能为空！",{icon:0,time:4000});
            return;
        }else if(business_Credit == "" ||  business_Credit == undefined){
            layer.msg("统一社会信用码不能为空！",{icon:0,time:4000});
            return;
        }else if(business_license == "" ||  business_license == undefined){
            layer.msg("营业执照不能为空！",{icon:0,time:4000});
            return;
        }else if(business_Legal == "" ||  business_Legal == undefined){
            layer.msg("法定代表人不能为空！",{icon:0,time:4000});
            return;
        }else if(business_tel == "" ||  business_tel == undefined){
            layer.msg("联系方式不能为空！",{icon:0,time:4000});
            return;
        }else if(business_create == "" ||  business_create == undefined){
            layer.msg("成立日期不能为空！",{icon:0,time:4000});
            return;
        }else if(consume == "" ||  consume == undefined){
            layer.msg("人均消费不能为空！",{icon:0,time:4000});
            return;
        }else if(address == "" ||  address == undefined){
            layer.msg("住所不能为空！",{icon:0,time:4000});
            return;
        }else {
            $.post('/businesinfo/upgradeBusines', {
                "tab":tab,
                "user_encryptId":user_encryptId,
                "business_Legal":business_Legal,
                "business_Credit":business_Credit,
                "business_license":business_license,
                "business_tel":business_tel,
                "business_create":business_create,
                "business_type":business_type,
                "farm_tour_type":farm_tour_type,
                "Business_area":Business_area,
                "dining_reception":dining_reception,
                "room":room,
                "scale":scale,
                "consume":consume,
                "city":city,
                "district":district,
                "address":address,
                "intr_info":intr_info,
                "bus_route":bus_route,
                "Self_route":Self_route,
                "Remarks":Remarks,
                "CompanyName":CompanyName,
                "tradestatus":tradestatus,
                "Type_encryptId":Type_encryptId
            }, function (data) {
                if (data.status == 0 && data.msg == 'ok') {

                    layer.msg("提交升级成功!",{time:2000});
                    mclose();
                    getData();
                    var size = "usermanage/business-list.html".length;
                    window.parent.addTab_father("商家列表", "usermanage/business-list.html", size);

                } else {
                    if(data.msg==null||data.msg==""){
                        layer.alert("接口出现错误！", {icon: 2})
                    }else{
                        layer.alert(data.msg, {icon: 2})
                    }
                }
            })
        }

    }else {
        //升级为景区商家
        var business_Legal = $.trim($("#tour_Legalperson").val());//法定代表人
        var business_Credit = $.trim($("#tour_business_code").val());//统一社会信用码
        var business_license = $.trim($("#tour_license_url").val());//营业执照
        var business_tel = $.trim($("#tour_tel").val());//联系方式
        var business_create = $.trim($("#tour_start").val());//成立日期
        // var business_type = $.trim($("#tour_Mertype_name").val());//商户类型
        var business_type = $("#tour_Mertype_name").attr("data");//商户类型
        var farm_tour_type = $("#tour_Mertype option:selected").attr("value");//景区类型

        var tour_Ticket = $.trim($("#tour_Ticket").val());//门票价格
        var tour_kftime = $.trim($("#tour_kftime").val());//开放时间
        var scenic_suitList = new Array(); //适合人群
        var scenic_suitIdList = new Array(); //适合人群加密id
        $("#tour_merch_type").find("input[type=checkbox]:checked").each(function () {
            if ($.inArray($(this).attr("value"), scenic_suitList) == -1) {
                scenic_suitList.push($(this).attr("value"));
            }
            if ($.inArray($(this).attr("encryptid"), scenic_suitIdList) == -1) {
                scenic_suitIdList.push($(this).attr("encryptid"));
            }
        });
        var tour_season = $("#tour_season option:selected").attr("value");  //最佳季节

        var city = $("#tour_province option:selected").attr("value");  //城市名称
        var district = $("#tour_area option:selected").attr("value");  //区县
        var address = $.trim($("#tour_address").val());//住所

        var intr_info = $.trim($("#tour_introduce").val());//景区介绍
        var bus_route = $.trim($("#tour_bus_line").val());//公交路线
        var Self_route = $.trim($("#tour_Self_driving_line").val());//自驾路线
        var Remarks = $.trim($("#tour_remarks").val());//备注
        var CompanyName = $.trim($("#tour_business_name").val());//企业名称
        var scenic_grade = $("#tour_grade option:selected").attr("value");//景区等级
        var Type_encryptId = $("#tour_Mertype option:selected").attr("encryptid");//景区商户类型加密id

        if(CompanyName == "" || CompanyName == undefined){
            layer.msg("企业名称不能为空！",{icon:0,time:4000});
            return;
        }else if(business_Credit == "" ||  business_Credit == undefined){
            layer.msg("统一社会信用代码不能为空！",{icon:0,time:4000});
            return;
        }else if(business_license == "" ||  business_license == undefined){
            layer.msg("营业执照不能为空！",{icon:0,time:4000});
            return;
        }else if(business_Legal == "" ||  business_Legal == undefined){
            layer.msg("法定代表人不能为空！",{icon:0,time:4000});
            return;
        }else if(business_tel == "" ||  business_tel == undefined){
            layer.msg("联系方式不能为空！",{icon:0,time:4000});
            return;
        }else if(business_create == "" ||  business_create == undefined){
            layer.msg("成立日期不能为空！",{icon:0,time:4000});
            return;
        }else if(consume == "" ||  consume == undefined){
            layer.msg("人均消费不能为空！",{icon:0,time:4000});
            return;
        }else if(address == "" ||  address == undefined){
            layer.msg("住所不能为空！",{icon:0,time:4000});
            return;
        }else {
            $.post('/businesinfo/upgradeSecBusines', {
                "tab":tab,
                "user_encryptId":user_encryptId,
                "business_Legal":business_Legal,
                "business_Credit":business_Credit,
                "business_license":business_license,
                "business_tel":business_tel,
                "business_create":business_create,
                "business_type":business_type,
                "farm_tour_type":farm_tour_type,
                "scenic_Ticket":tour_Ticket,
                "tour_kftime":tour_kftime,
                "scenic_suit":scenic_suitList.join(","),
                "sceni_suit_encryptId":scenic_suitIdList.join(","),
                "scenic_season":tour_season,
                "city":city,
                "district":district,
                "address":address,
                "intr_info":intr_info,
                "bus_route":bus_route,
                "Self_route":Self_route,
                "Remarks":Remarks,
                "CompanyName":CompanyName,
                "scenic_grade":scenic_grade,
                "Type_encryptId":Type_encryptId
            }, function (data) {
                if (data.status == 0 && data.msg == 'ok') {

                    layer.msg("提交升级成功!",{time:2000});
                    mclose();
                    getData();
                    var size = "usermanage/business-list.html".length;
                    window.parent.addTab_father("商家列表", "usermanage/business-list.html", size);

                } else {
                    if(data.msg==null||data.msg==""){
                        layer.alert("接口出现错误！", {icon: 2})
                    }else{
                        layer.alert(data.msg, {icon: 2})
                    }
                }
            })
        }
    }

    
}

$(function () {
    //农家乐营业执照上传
    layui.use('upload', function () {
        var upload = layui.upload;
        var ii = null;
        //执行实例
        var uploadInst = upload.render({
            elem: '#farm_license_file' //绑定元素
            , url: '/xw/imgfile' //上传接口 (调用原本可以上传的url，并没有将数据存入数据库中)
            , accept: 'file'
            , before: function (obj) { //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
                ii = layer.load(2); //上传loading
            }
            , done: function (res) {
                layer.close(ii);
                //上传完毕回调
                if (res.status == "0") {
                    layer.msg("文件上传成功");
                    $("#farm_license_url").val(res.fileurl);
                    $("#farm_license_img").attr("src",res.fileurl+"?x-oss-process=style/tuImgStyle");
                    $("#farm_license_img").show();
                } else {
                    layer.alert("上传文件失败！", {icon: 1})
                }
            }
            , error: function () {
                //请求异常回调
                layer.close(ii);
                layer.alert("上传文件发生异常！", {icon: 1})
            }
        });
    });

    //景区营业执照上传
    layui.use('upload', function () {
        var upload = layui.upload;
        var ii = null;
        //执行实例
        var uploadInst = upload.render({
            elem: '#tour_license_file' //绑定元素
            , url: '/xw/imgfile' //上传接口 (调用原本可以上传的url，并没有将数据存入数据库中)
            , accept: 'file'
            , before: function (obj) { //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
                ii = layer.load(2); //上传loading
            }
            , done: function (res) {
                layer.close(ii);
                //上传完毕回调
                if (res.status == "0") {
                    layer.msg("文件上传成功");
                    $("#tour_license_url").val(res.fileurl);
                    $("#tour_license_img").attr("src",res.fileurl+"?x-oss-process=style/tuImgStyle");
                    $("#tour_license_img").show();
                } else {
                    layer.alert("上传文件失败！", {icon: 1})
                }
            }
            , error: function () {
                //请求异常回调
                layer.close(ii);
                layer.alert("上传文件发生异常！", {icon: 1})
            }
        });
    });
})


/**************************************商家升级-end*******************************************************/





/**************************************用户详情-start*******************************************************/
//点击详情 - 跳转用户详情信息页面
function question_user(user_id,user_encryptId) {
    setcookie("user_id",user_id,1,"/");//用户加密id
    setcookie("user_encryptId",user_encryptId,1,"/");//用户加密id
	var size = "usermanage/user_info_new.html".length;
	window.parent.addTab_father("客户详情", "usermanage/user_info_new.html", size);
}

//点击详情 - 跳转商家详情信息页面
function question_business(business_encryptId,shop_encryptId,businessTypeid) {
    setcookie("business_encryptId",business_encryptId,1,"/");//商家加密id
    setcookie("shop_encryptId",shop_encryptId,1,"/"); //店铺加密id
    if(businessTypeid == "1"){
        var size = "merchant/merchant_information_new.html".length;
        window.parent.addTab_father("农家乐商家详情", "merchant/merchant_information_new.html", size);
    }else if(businessTypeid == "2"){
        var size = "tourist/tour_info_new.html".length;
        window.parent.addTab_father("景区商家详情", "tourist/tour_info_new.html", size);
    }
}

/**************************************用户详情-end*******************************************************/


/**************************************公共方法-start*******************************************************/

//获取全部的主题游信息列表
var allSceThemetypelist = new Array();
function getThemelist() {
	$("#userHobbyZt").html("");
    $("#tour_Mertype").html("");
    $.post('/SceThemeType/getAllSceThemetype', {}, function (data) {
        if (data.status == 0 && data.msg == 'ok') {
           var list = data.list;
            allSceThemetypelist = data.list;
           var str = "";
           if(list.length>0){
           		for(var i=0;i<list.length;i++){
           			str += "<input type=\"checkbox\" name=\"userHobbyZt\" lay-skin=\"primary\" value='"+list[i].title+"' title='"+list[i].title+"' encryptId='"+list[i].encryptId+"' themeId='"+list[i].themeId+"'>";
				}
				$("#userHobbyZt").html(str);
		   }
        } else {
            if(data.msg==null||data.msg==""){
                layer.alert("接口出现错误！", {icon: 2})
            }else{
                layer.alert(data.msg, {icon: 2})
            }
        }
    })

}

//获取景区游玩类型
var allScePlaytypelist = new Array();
function getSecPlayTypelist() {
    $("#userHobbyYw").html("");
    $.post('/ScePlayType/getAllScePlaytype', {}, function (data) {
        if (data.status == 0 && data.msg == 'ok') {
            var list = data.list;
            allScePlaytypelist = data.list;
            var str = "";
            if(list.length>0){
                for(var i=0;i<list.length;i++){
                    str += "<input type=\"checkbox\" name=\"userHobbyYw\" lay-skin=\"primary\" value='"+list[i].title+"' title='"+list[i].title+"' encryptId='"+list[i].encryptId+"' sceplayId='"+list[i].sceplayId+"'>";
                }
                $("#userHobbyYw").html(str);
            }
        } else {
            if(data.msg==null||data.msg==""){
                layer.alert("接口出现错误！", {icon: 2})
            }else{
                layer.alert(data.msg, {icon: 2})
            }
        }
    })
}


//获取农家乐商户类型
function getAllfarmMertype() {
    $("#farm_Mertype").html("");
    $.post('/farmMerType/getAllfarmMertype', {}, function (data) {
        if (data.status == 0 && data.msg == 'ok') {
            var list = data.list;
            var str = "";
            if(list.length>0){
                for(var i=0;i<list.length;i++){
                    str += "<option encryptId='"+list[i].encryptId+"' value='"+list[i].title+"'>"+list[i].title+"</option>";
                }
                $("#farm_Mertype").html(str);
            }
        } else {
            if(data.msg==null||data.msg==""){
                layer.alert("接口出现错误！", {icon: 2})
            }else{
                layer.alert(data.msg, {icon: 2})
            }
        }
    })
}


//获取景区商户类型
function getAllSerMertype() {
    $("#tour_Mertype").html("");
    $.post('/SceMerType/getAllSerMertype', {}, function (data) {
        if (data.status == 0 && data.msg == 'ok') {
            var list = data.list;
            var str = "";
            if(list.length>0){
                for(var i=0;i<list.length;i++){
                    str += "<option encryptId='"+list[i].encryptId+"' value='"+list[i].title+"'>"+list[i].title+"</option>";

                }
                $("#tour_Mertype").html(str);
            }
        } else {
            if(data.msg==null||data.msg==""){
                layer.alert("接口出现错误！", {icon: 2})
            }else{
                layer.alert(data.msg, {icon: 2})
            }
        }
    })
}

//适合人群
function getAllCrowd() {
    $("#tour_merch_type").html("");
    $.post('/Crowd/getAllCrowd', {}, function (data) {
        if (data.status == 0 && data.msg == 'ok') {
            var list = data.list;
            var str = "";
            if(list.length>0){
                for(var i=0;i<list.length;i++){
                    str += "<input type=\"checkbox\" name=\"tourType\" lay-skin=\"primary\" value='"+list[i].title+"' title='"+list[i].title+"' encryptId='"+list[i].encryptId+"' CrowdId='"+list[i].CrowdId+"'>";
                }
                $("#tour_merch_type").html(str);
            }
        } else {
            if(data.msg==null||data.msg==""){
                layer.alert("接口出现错误！", {icon: 2})
            }else{
                layer.alert(data.msg, {icon: 2})
            }
        }
    })
}


//时间选择控制器
function timesearch() {

	layui.use('laydate', function() {
		var laydate = layui.laydate;

		//日期范围
		laydate.render({
			elem: '#date1'
			,range: true
            ,btns: ['confirm']
            ,max: time()//设置最大日期为当前日期时间
            ,ready: function(date){
                //默认控件打开的时候调用一下向左点击的事件，则显示的日期范围为左边为上个月月份，右边为当月月份
                $(".laydate-main-list-0 .laydate-prev-m").click();
            }
			,startDate: new Date().format('yyyy-MM-dd')
			,endDate: new Date().format('yyyy-MM-dd')
			,done: function(value, date, endDate) { //选择好日期的回调
				startDate = starttime = value.substring(0, 10);
				endDate = endtime = value.substring(13, 23);
				pageindex = 1;
                $("#date1").html(startDate+" - "+endDate);
                $(".select_time1 li").removeClass("blue_color");
				//获取数据
				$("#first_button").click();
			}
		});
	});

}
/**
 * 获取当前时间
 * @returns {String}
 */
function time() {
	var myDate = new Date();
	var year = myDate.getFullYear();
	var month = parseInt(myDate.getMonth() + 1);
	var day = myDate.getDate();
	var timedate = year + "-" + month + "-" + day;
	return timedate;
};

function time1() {
	var myDate = new Date();
	var year = myDate.getFullYear();
	var month = parseInt(myDate.getMonth() + 1);
	var day = parseInt(myDate.getDate() - 1);
	var timedate = year + "-" + month + "-" + day;
	return timedate;
};
/**
 * 当前时间段
 */
function timequantum(n) {
	var myDate = new Date();
	var year = myDate.getFullYear();
	var month = parseInt(myDate.getMonth() + 1);
	var day = myDate.getDate();
	if(n > day) {
		if(month > 1) {
			month = parseInt(month - 1);
		} else {
			year = parseInt(year - 1);
		}
	} else {
		day = parseInt(day - n);
	}
	var timedate = year + "-" + month + "-" + day;
	return timedate;
}

function DateDiff(sDate1, sDate2) { //sDate1和sDate2是yyyy-MM-dd格式
	var aDate, oDate1, oDate2, iDays;
	aDate = sDate1.split("-");
	oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]); //转换为yyyy-MM-dd格式
	aDate = sDate2.split("-");
	oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]);
	iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24); //把相差的毫秒数转换为天数

	return iDays; //返回相差天数
}
Date.prototype.format = function(format) {
	var o = {
		"M+": this.getMonth() + 1, //month
		"d+": this.getDate(), //day
		"h+": this.getHours(), //hour
		"m+": this.getMinutes(), //minute
		"s+": this.getSeconds(), //second
		"q+": Math.floor((this.getMonth() + 3) / 3), //quarter
		"S": this.getMilliseconds() //millisecond
	}
	if(/(y+)/.test(format)) format = format.replace(RegExp.$1,
		(this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for(var k in o)
		if(new RegExp("(" + k + ")").test(format))
			format = format.replace(RegExp.$1,
				RegExp.$1.length == 1 ? o[k] :
				("00" + o[k]).substr(("" + o[k]).length));
	return format;
}
/**************************************公共方法-end*******************************************************/